import os
from PIL import Image, ImageSequence
import shutil
import hashlib

OUTPUT_IMAGE_MAX_SIZE = (128, 64)

working_dir = os.path.dirname(__file__)
pbm_path = f'{working_dir}/pbm/'


def get_bin_table(threshold=105):
	'''获取灰度转二值的映射表，0 表示白色，1 表示黑色'''
	def append(value):
		return 1 if value < threshold else 0

	return list(map(append, range(256)))

def choose_a_gif(root):
	def list_files(root):
		files=[]
		for dir in os.listdir(root):
			fullpath = ('' if root == '/' else root) + '/' + dir
			if os.stat(fullpath)[0] & 0x4000 != 0:
				files.extend(list_files(fullpath))
			else:
				if dir.endswith('.gif'):
					files.append(fullpath)
		return files

	gif_files = list_files(root)

	if len(gif_files) > 0:
		print('\ngif file list')
		for index,file in enumerate(gif_files, start=1):
			print('    [{}] {}'.format(index, file))

		selected=None
		while True:
			try:
				selected=int(input('Choose a file: '))
				print('')
				assert type(selected) is int and 0 < selected <= len(gif_files)
				break
			except KeyboardInterrupt:
				exit()
			except:
				pass

		if selected:
			return gif_files[selected - 1]
	else:
		print('no gif file found')
		exit()

def deduplicate(root):
	image_md5_list = []
	image_file_list = os.listdir(root)

	if len(image_file_list) == 1:
		return

	for filename in image_file_list:
		md5 = hashlib.md5()
		hash_value = None
		image_filename = f'{root}{filename}'

		with open(image_filename, 'rb') as image:
			md5.update(image.read())
			hash_value = md5.hexdigest()

		if hash_value in image_md5_list:
			os.remove(image_filename)
		else:
			image_md5_list.append(hash_value)


if __name__ == '__main__':
	gif_filename = choose_a_gif(working_dir)

	if os.path.exists(pbm_path):
		shutil.rmtree(pbm_path, ignore_errors=True)

	os.mkdir(pbm_path)

	table = get_bin_table(255 - 105)

	temp = Image.open(gif_filename)
	temp.thumbnail(OUTPUT_IMAGE_MAX_SIZE)
	output_size = temp.size
	temp.close()

	with Image.open(gif_filename) as gif_image:
		for index, frame in enumerate(ImageSequence.Iterator(gif_image), start=1):
			output = frame.resize(output_size).convert('L').point(table, '1')
			# output = output.transpose(Image.FLIP_TOP_BOTTOM)
			output.save(pbm_path + '{:04d}.pbm'.format(index))

	# deduplicate(pbm_path)
